package com.woniuxy.buyer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.buyer.mapper.UserMapper;
import com.woniuxy.buyer.service.AuthService;
import com.woniuxy.common.entity.User;
import com.woniuxy.common.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 认证服务实现
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public String login(String username, String password) {
        // 根据用户名查询用户
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user = userMapper.selectOne(wrapper);

        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        if (user.getStatus() != 1) {
            throw new RuntimeException("用户已被禁用");
        }

        // 验证密码（这里假设密码是明文存储，实际应该用BCrypt加密）
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(password, user.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        // 生成JWT Token
        return jwtUtils.generateToken(
            String.valueOf(user.getId()),
            user.getUsername(),
            user.getRole()
        );
    }

    @Override
    public User getUserByToken(String token) {
        if (!jwtUtils.validateToken(token)) {
            return null;
        }

        String userId = jwtUtils.getUserIdFromToken(token);
        return userMapper.selectById(Long.parseLong(userId));
    }

    @Override
    public boolean validateUserRole(String token, String expectedRole) {
        if (!jwtUtils.validateToken(token)) {
            return false;
        }

        String role = jwtUtils.getRoleFromToken(token);
        return expectedRole.equals(role);
    }
}
